package com.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.util.StringUtils;
import com.example.demo.auth.constant.SessionConstants;


public class CookieUtils {
	private static String basedomain = "/";

	private static boolean isHttpOnlySupportChecked = false;
    private static boolean isHttpOnlySupport = false;

	public void setBasedomain(String basedomain) {
		CookieUtils.basedomain = basedomain;
	}
	/**
	 * 设置cookie
	 * 
	 * @param response
	 * @param name cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期 以秒为单位 -1浏览器进程 0删除
	 */
	public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		if(StringUtils.isEmpty(basedomain)){
			cookie.setDomain(basedomain);
		}
		cookie.setPath("/");
        cookie.setMaxAge(maxAge);

        if(!isHttpOnlySupportChecked){
            isHttpOnlySupport = PropertyUtils.isWriteable(cookie,"httpOnly");
            isHttpOnlySupportChecked = true;
        }
        if(isHttpOnlySupport){
            cookie.setHttpOnly(true);
        }

		response.addCookie(cookie);
	}
    public static void addCookie(HttpServletResponse response, String name, String value) {
        addCookie(response, name, value, SessionConstants.MAX_SESSION_AGE);
    }
    public static void addCookieLongTime(HttpServletResponse response, String name, String value) {
        addCookie(response, name, value, SessionConstants.LONG_SESSION_AGE);
    }

    /**
     * 清除cookie
     * @param response
     * @param name
     */
    public static void removeCookie(HttpServletResponse response, String name) {
        addCookie(response, name, "",0);
    }
	/**
	 * 根据名字获取cookie
	 * 
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}

	/**
	 * 根据名字获取cookie值
	 * 
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	public static String getCookieValueByName(HttpServletRequest request, String name) {
		Cookie cookie = getCookieByName(request, name);
		if (cookie == null) {
			return null;
		}
		return cookie.getValue();
	}
}
